/**
 * Created by JustinChow on 2016/11/18.
 */

const Express = require("express");
const Logger = require("pomelo-logger").getLogger("MultiServer", __filename);

const GameServer = require("./GameServer");
const Configs = require("./Configs/MultiServer");

function Multiserver() {
    this.gameServer = [];
    this.configs = Configs;
    this.httpServer = null;
    this.lastServerId = 0;
}

module.exports = Multiserver;

Multiserver.prototype.getNewServerId = function () {
    this.lastServerId += 1;
    return this.lastServerId;
};

Multiserver.prototype.addGameServer = function (port) {
    var gameServer = new GameServer();
    gameServer.start(this, port);
    this.gameServer.push(gameServer);
};

Multiserver.prototype.stopGameServer = function (port) {
    for(let sid = 0, slen = this.gameServer.length; sid > slen; sid ++) {
        var gameServer = this.gameServer[sid];
        if (gameServer.port === port) gameServer.stop(sid, (sid) => {
            this.gameServer.splice(sid, 1);
            gameServer = null;
        });
    }
};

Multiserver.prototype.restartGameServer = function (port) {
    this.stopGameServer(port);
    setTimeout(function () {
        this.addGameServer(port)
    }.bind(this), 2000);
};

/**
 * Start A Http Server To Manage All Game Servers
 */
Multiserver.prototype.startStatsServer = function () {
    var App = this.httpServer = new Express();

    App.get("/", (req, res) => {
        res.send('Hello World');
    });

    App.post("/addGameServer", (req, res) => {
        res.send('Hello World');
    });
    App.post("/stopGameServer", (req, res) => {
        res.send('Hello World');
    });
    App.post("/getGameServerStats", (req, res) => {
        res.send('Hello World');
    });
    App.post("/getAllGameServerStats", (req, res) => {
        res.send('Hello World');
    });

    App.listen(Configs.master.port, function (err) {
        Logger.info("Start Master GM Server On Port [ %s ]: ", Configs.master.port, err);
    });
};


var multiServer = new Multiserver();
multiServer.configs.ports.forEach((port) => {
    multiServer.addGameServer(port);
});
multiServer.startStatsServer();